package com.kamfu.makingjavafunctional.example01;

import com.kamfu.function.common.Function;
import com.kamfu.makingjavafunctional.Result01;

import java.util.regex.Pattern;

/**
 * 错误处理更好的程序
 */
public class EmailValidation03 {

    static Pattern emailPattern =
            Pattern.compile("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$");

    static Function<String, Result01> emailChecker = s -> {
        if (s == null) {
            return new Result01.Failure("email must not be null");
        } else if (s.length() == 0) {
            return new Result01.Failure("email must not be empty");
        } else if (emailPattern.matcher(s).matches()) {
            return new Result01.Success();
        } else {
            return new Result01.Failure("email " + s + " is invalid.");
        }
    };
    static void validate(String s) {
        Result01 result = emailChecker.apply(s);
        if (result instanceof Result01.Success) {
            sendVerificationMail(s);
        } else {
            logError(((Result01.Failure) result).getMessage());
        }
    }

    private static void sendVerificationMail(String s) {
        System.out.println("Verification mail sent to " + s);
    }

    private static void logError(String s) {
        System.err.println("Error message logged: " + s);
    }


    public static void main(String... args) {
        validate("this.is@my.email");
        validate(null);
        validate("");
        validate("john.doe@acme.com");
    }
}
